package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取到响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.获取到请求的URL路径,判断是否是登录请求
        if (request.getURI().getPath().contains("/admin/login")){
            //登录请求直接放行
            return chain.filter(exchange);
        }
        //4.获取到请求的头的信息
        HttpHeaders headers = request.getHeaders();
        //5.获取到token的值,
        String token = headers.getFirst("token");
        //判断token是否为空
        if (StringUtils.isEmpty(token)){
            //如果为空,直接返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.token值不为空,进行编译操作
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //编译报错,直接返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
